import NextAuth, { NextAuthOptions, User } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'

const SERVER_BASEURL = process.env.NEXT_PUBLIC_SERVER_BASEURL
if (!SERVER_BASEURL) {
  throw new Error('Missing environment variables')
}

interface LoginCredentials {
  email: string
  password: string
  apiSecretKey: string
  clientIp: string
}

interface LoginResponse {
  code: string
  message: string
  data?: User
}

const normalLogIn = async ({
  email,
  password,
  apiSecretKey,
  clientIp,
}: LoginCredentials): Promise<LoginResponse> => {
  try {
    const response = await fetch(`${SERVER_BASEURL}app/user/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'api-secret-key': apiSecretKey,
        'x-forwarded-for': clientIp,
      },
      body: JSON.stringify({ email, password }),
    })
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const res = (await response.json()) as LoginResponse

    if (res.code !== 'G_0000') throw new Error(res.code)

    return res
  } catch (err) {
    return {
      code: 'ERROR',
      message: err instanceof Error ? err.message : 'Unknown error occurred',
    }
  }
}

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      credentials: {},
      name: 'Credentials',
      async authorize(credentials, req) {
        if (!credentials) {
          throw new Error('No credentials provided')
        }

        const forwardedFor = req.headers?.['x-forwarded-for']
        const clientIp =
          typeof forwardedFor === 'string' ? forwardedFor.split(/, /)[0] : '127.0.0.1'

        const params = {
          ...credentials,
          clientIp,
        } as LoginCredentials

        const res = await normalLogIn(params)

        return res.data as User
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: 'jwt',
    maxAge: 60 * 60 * 24 * 30, // 30 days
  },
  pages: {
    signIn: '/sign-in',
    error: '/sign-in', // 防止跳 404
  },
  callbacks: {
    signIn({ user, account }) {
      if (account?.provider === 'credentials') {
        if (user) return true
        return false
      }
      return false
    },
    jwt({ token, user }) {
      if (user) {
        // token.id = user.id
        token.email = user.email
        token.name = user.name
      }
      return token
    },
    session({ session, token }) {
      if (session.user) {
        // session.user.id = token.id as string
        session.user.email = token.email as string
        session.user.name = token.name as string
      }
      return session
    },
  },
}

export default NextAuth(authOptions)
